package com.isunland.managesystem.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import com.bugtags.library.Bugtags;
import com.orhanobut.logger.Logger;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

public class LogUtil {
  public static final String ROOT =
      Environment.getExternalStorageDirectory().getPath() + "/finddreams/"; // SD卡中的根目录
  private static final boolean isSaveLog = false; // 是否把保存日志到SD卡中
  private static final String PATH_LOG_INFO = ROOT + "info/";
  private static final ThreadLocal<ReusableFormatter> thread_local_formatter =
      new ThreadLocal<ReusableFormatter>() {
        protected ReusableFormatter initialValue() {
          return new ReusableFormatter();
        }
      };
  public static String customTagPrefix = ""; // 自定义Tag的前缀，可以是作者名
  /**
   * 自定义的logger
   */
  public static CustomLogger customLogger;
  // 容许打印日志的类型，默认是true，设置为false则不打印
  private static boolean allowD = true;
  private static boolean allowE = true;
  private static boolean allowI = true;
  private static boolean allowV = true;
  private static boolean allowW = true;
  private static boolean allowWtf = true;

  private LogUtil() {
  }

  public static void allowLog(boolean isAllow) {
    allowD = isAllow;
    allowE = isAllow;
    allowI = isAllow;
    allowV = isAllow;
    allowW = isAllow;
    allowWtf = isAllow;
  }

  /**
   * 是否禁用log日志.
   */
  // public static void forbiddenLog(boolean isForbidden) {
  // if (isForbidden) {
  // allowD = false;
  // allowE = false;
  // allowI = false;
  // allowV = false;
  // allowW = false;
  // allowWtf = false;
  // }else {
  // allowD = true;
  // allowE = true;
  // allowI = true;
  // allowV = true;
  // allowW = true;
  // allowWtf = true;
  // }
  // }
  private static String generateTag(StackTraceElement caller) {
    String tag = "%s.%s(Line:%d)"; // 占位符
    String callerClazzName = caller.getClassName(); // 获取到类名
    callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
    tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber()); // 替换
    tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":" + tag;
    return tag;
  }

  public static void d(String content) {
    if (!allowD) return;
    if (content == null) {
      content = "null";
    }
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);

    if (customLogger != null) {
      customLogger.d(tag, content);
    } else {
      Log.d(tag, content);
    }
    // 上传log信息.
    Bugtags.log(tag + content);
  }

  public static void d(String useLessTag, String content) {
    if (!allowD) return;
    if (content == null) {
      content = "null";
    }
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);

    if (customLogger != null) {
      customLogger.d(tag, content);
    } else {
      Log.d(tag, content);
    }
    // 上传log信息.
    Bugtags.log(tag + content);
  }

  public static void d(String content, Throwable tr) {
    if (content == null) {
      content = "null";
    }
    if (!allowD) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);

    if (customLogger != null) {
      customLogger.d(tag, content, tr);
    } else {
      Log.d(tag, content, tr);
    }
    // 上传log信息.
    Bugtags.log(tag + content);
  }

  public static void e(String content) {
    if (content == null) content = "null";
    if (!allowE) return;
    Logger.e(content);
    //StackTraceElement caller = getCallerStackTraceElement();
    //String tag = generateTag(caller);
    //// 上传log信息.
    //Bugtags.log(tag + content);
    //if (customLogger != null) {
    //    customLogger.e(tag, content);
    //} else {
    //    Log.e(tag, content);
    //}
    //if (isSaveLog) {
    //    point(PATH_LOG_INFO, tag, content);
    //}

  }

  public static void e(String useLessTag, String content) {
    if (content == null) {
      content = "null";
    }
    if (!allowE) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.e(tag, content);
    } else {
      Log.e(tag, content);
    }
    if (isSaveLog) {
      point(PATH_LOG_INFO, tag, content);
    }
  }

  public static void e(String content, Throwable tr) {
    if (content == null) content = "null";
    if (!allowE) return;
    Logger.e(tr, content);
    //Bugtags.log( content);

  }

  public static void e(String useLessTag, String content, Throwable tr) {
    if (content == null) {
      content = "null";
    }
    if (!allowE) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.e(tag, content, tr);
    } else {
      Log.e(tag, content, tr);
    }
    if (isSaveLog) {
      point(PATH_LOG_INFO, tag, tr.getMessage());
    }
  }

  public static void json(String tag, String content) {
    if (tag == null) tag = "null";
    if (content == null) content = "null";
    if (!allowI) return;
    Logger.t(tag).json(content);
    //StackTraceElement caller = getCallerStackTraceElement();
    //String tag = generateTag(caller);
    // 上传log信息.
    //Bugtags.log(tag + content);
    //if (customLogger != null) {
    //    customLogger.i(tag, content);
    //
    //} else {
    //    Log.i(tag, content);
    //}

  }

  public static void i(String content) {
    if (content == null) content = "null";
    if (!allowI) return;
    Logger.i(content);
  }

  /**
   * @param content 内容
   * @param index 控制打印元素.因为父类中想打印实现类的元素.
   */
  public static void i(String content, int index) {
    if (content == null) {
      content = "null";
    }

    if (!allowI) return;
    StackTraceElement caller;
    if (index > 0) {
      caller = getCallerStackTraceElement(index);
    } else {

      caller = getCallerStackTraceElement();
    }
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.i(tag, content);
    } else {
      Log.i(tag, content);
    }
  }

  public static void i(String useLessTag, String content) {

    if (content == null) content = "null";
    if (!allowI) return;

    Logger.t(useLessTag).i(content);
  }

  public static void d(String useLessTag, Object content) {

    if (!allowD) return;

    Logger.t(useLessTag).d(content);
  }

  public static void i(String content, Throwable tr) {
    if (content == null) {
      content = "null";
    }

    if (!allowI) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.i(tag, content, tr);
    } else {
      Log.i(tag, content, tr);
    }
  }

  public static void v(String content) {
    if (content == null) {
      content = "null";
    }
    if (!allowV) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.v(tag, content);
    } else {
      Log.v(tag, content);
    }
  }

  public static void v(String useLessTag, String content) {
    if (content == null) {
      content = "null";
    }
    if (!allowV) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.v(tag, content);
    } else {
      Log.v(tag, content);
    }
  }

  public static void v(String content, Throwable tr) {
    if (content == null) {
      content = "null";
    }
    if (!allowV) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.v(tag, content, tr);
    } else {
      Log.v(tag, content, tr);
    }
  }

  public static void w(String content) {
    if (content == null) {
      content = "null";
    }
    if (!allowW) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.w(tag, content);
    } else {
      Log.w(tag, content);
    }
  }

  public static void w(String useLessTag, String content) {
    if (content == null) {
      content = "null";
    }
    if (!allowW) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.w(tag, content);
    } else {
      Log.w(tag, content);
    }
  }

  public static void w(String content, Throwable tr) {
    if (content == null) {
      content = "null";
    }
    if (!allowW) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.w(tag, content, tr);
    } else {
      Log.w(tag, content, tr);
    }
  }

  public static void w(Throwable tr) {

    if (!allowW) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);

    if (customLogger != null) {
      customLogger.w(tag, tr);
    } else {
      Log.w(tag, tr);
    }
  }

  public static void wtf(String content) {
    if (content == null) {
      content = "null";
    }
    if (!allowWtf) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.wtf(tag, content);
    } else {
      Log.wtf(tag, content);
    }
  }

  public static void wtf(String content, Throwable tr) {
    if (content == null) {
      content = "null";
    }
    if (!allowWtf) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);
    // 上传log信息.
    Bugtags.log(tag + content);
    if (customLogger != null) {
      customLogger.wtf(tag, content, tr);
    } else {
      Log.wtf(tag, content, tr);
    }
  }

  public static void wtf(Throwable tr) {

    if (!allowWtf) return;
    StackTraceElement caller = getCallerStackTraceElement();
    String tag = generateTag(caller);

    if (customLogger != null) {
      customLogger.wtf(tag, tr);
    } else {
      Log.wtf(tag, tr);
    }
  }

  private static StackTraceElement getCallerStackTraceElement() {
    return Thread.currentThread().getStackTrace()[4];
  }

  private static StackTraceElement getCallerStackTraceElement(int index) {
    StackTraceElement[] array = Thread.currentThread().getStackTrace();
    if ((array.length - 1) > index) {
      return Thread.currentThread().getStackTrace()[index];
    } else {
      return Thread.currentThread().getStackTrace()[4];
    }
  }

  public static void point(String path, String tag, String msg) {
    if (isSDAva()) {
      Date date = new Date();
      SimpleDateFormat dateFormat = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
      dateFormat.applyPattern("yyyy");
      path = path + dateFormat.format(date) + "/";
      dateFormat.applyPattern("MM");
      path += dateFormat.format(date) + "/";
      dateFormat.applyPattern("dd");
      path += dateFormat.format(date) + ".log";
      dateFormat.applyPattern("[yyyy-MM-dd HH:mm:ss]");
      String time = dateFormat.format(date);
      File file = new File(path);
      if (!file.exists()) createDipPath(path);
      BufferedWriter out = null;
      try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        out.write(time + " " + tag + " " + msg + "\r\n");
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          if (out != null) {
            out.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 根据文件路径 递归创建文件
   */
  public static void createDipPath(String file) {
    String parentFile = file.substring(0, file.lastIndexOf("/"));
    File file1 = new File(file);
    File parent = new File(parentFile);
    if (!file1.exists()) {
      parent.mkdirs();
      try {
        file1.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  public static String format(String msg, Object... args) {
    ReusableFormatter formatter = thread_local_formatter.get();
    return formatter.format(msg, args);
  }

  public static boolean isSDAva() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
        || Environment.getExternalStorageDirectory().exists()) {
      return true;
    } else {
      return false;
    }
  }

  public interface CustomLogger {
    void d(String tag, String content);

    void d(String tag, String content, Throwable tr);

    void e(String tag, String content);

    void e(String tag, String content, Throwable tr);

    void i(String tag, String content);

    void i(String tag, String content, Throwable tr);

    void v(String tag, String content);

    void v(String tag, String content, Throwable tr);

    void w(String tag, String content);

    void w(String tag, String content, Throwable tr);

    void w(String tag, Throwable tr);

    void wtf(String tag, String content);

    void wtf(String tag, String content, Throwable tr);

    void wtf(String tag, Throwable tr);
  }

  /**
   * A little trick to reuse a formatter in the same thread
   */
  private static class ReusableFormatter {

    private Formatter formatter;
    private StringBuilder builder;

    public ReusableFormatter() {
      builder = new StringBuilder();
      formatter = new Formatter(builder);
    }

    public String format(String msg, Object... args) {
      formatter.format(msg, args);
      String s = builder.toString();
      builder.setLength(0);
      return s;
    }
  }
}
